<template>
  <div ref="searchWarp" class="flex justify-between search-warp">
    <form-create
      class="searchForm"
      name="searchForm"
      v-model:api="searchRef"
      :option="searchOptions"
      :rule="searchDefaultData"
    >
      <slot> </slot>
      <template #type-searchBtn="scope"> </template>
    </form-create>
    <div class="flex pl-[24px]">
      <a-button type="link" @click="handleClickAdvanceBtn" v-if="filterShow">
        <span v-if="advanceShow">收起<UpOutlined class="text-[14px] ml-1" /></span>
        <span v-else>展开<DownOutlined class="text-[14px] ml-1" /></span>
      </a-button>
      <a-button type="primary" class="mr-3" @click="submitBtn">
        <template #icon> <SearchOutlined /> </template> 查询
      </a-button>
      <a-button @click="resetBtn">
        <template #icon> <ClearOutlined /> </template> 重置
      </a-button>
    </div>
  </div>
</template>

<script lang="tsx" setup>
import {
  ClearOutlined,
  SearchOutlined,
  DownOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import formCreate from "@form-create/ant-design-vue";
import { get, cloneDeep, debounce } from "lodash-es";
const props = defineProps({
  // searchRef: {}
  searchParams: {
    type: Object as PropType<any>,
    // required: true,
  },
  searchOptions: {
    type: Object as any,
    default: {
      form: {
        labelCol: { style: { width: "110px" } },
      },
      submitBtn: false,
      // submitBtn: {
      //   innerText: "搜索",
      //   labelCol: { span: 1 },
      //   // col: undefined,
      //   col: { span: 6 },
      //   wrap: {
      //     title: false,
      //   },
      // },
    },
  },
  searchData: {
    type: Array,
    default: () => [],
  },
  // 重置时，需要忽略的置为 null 的 key 的集合
  resetIgnoreKeys: {
    type: Array<string>,
    default: () => [],
  },
});

const emits = defineEmits([
  "on-change-search-params",
  "on-click-reset-btn",
  "on-click-refresh-btn",
  "update:searchParams",
]);

const colConfig = { xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 6 };

const searchDefaultData: any = computed(() => {
  props.searchData.forEach((item: any) => {
    if (!item.col) {
      item.col = colConfig;
    }
    if (item.type === "select") {
      item.props = {
        ...item.props,
        "show-search": true,
        filterOption: (input, option) => {
          const aisle =
            searchRef.value?.getRule &&
            searchRef.value?.getRule(item.field).props;
          const keyComputed = get(aisle, "fieldNames.label", "label");
          const valComputed = get(aisle, "fieldNames.value", "value");
          return (
            option[keyComputed]?.toLowerCase().indexOf(input.toLowerCase()) >= 0
          );
        },
      };
    }
    let props = {
      ...item.props,
      placeholder: get(
        item,
        "props.placeholder",
        item.type === "input"
          ? `请输入${item.title}`
          : item.type === "select"
          ? `请选择${item.title}`
          : undefined
      ),
      allowClear: true,
    };
    item.props = props;
    if (item.type === "searchBtn") {
      item.hidden = true;
    }
  });

  return props.searchData;
});

// console.log('getApi',formCreate.util.getApi('form'));
const searchWarp = ref<any>({});
const searchRef = ref<any>({});



// console.log(searchRef.value,props.searchOptions);

const submitBtn = () => {
  searchRef.value.submit((formData, fApi) => {
    emits("update:searchParams", formData);
    emits("on-change-search-params", props.searchParams);
  });
};
// const search = cloneDeep()

const resetBtn = () => {
  // searchRef.value.submit((formData, fApi) => {
  //   console.log("cloneDeep", search, props.searchParams);
  //   // emits("update:searchParams", { ...formData, ...props.searchParams });
  //   // emits("on-change-search-params", props.searchParams);
  // });

  // console.log(searchRef.value.getData(), get(props, 'resetIgnoreKeys.length', 0));
  searchRef.value.resetFields();
  const formData = searchRef.value.coverValue({});
  emits("update:searchParams", formData);
  emits("on-click-reset-btn");
};


const columnsPerRow = ref<any>(null);
const filterShow = ref<any>(false);
const advanceShow = ref<any>(true);
const displayList = ref<any>([]);

// 根据屏幕宽度计算当前 span
const getSpanByBreakpoint = (width) => {
  if (width < 576) return colConfig.xs;
  if (width >= 576 && width < 768) return colConfig.sm;
  if (width >= 768 && width < 992) return colConfig.md;
  if (width >= 992 && width < 1200) return colConfig.lg;
  if (width >= 1200 && width < 1600) return colConfig.xl;
  return colConfig.xxl;
};

const handleClickAdvanceBtn = () => {
  advanceShow.value = !advanceShow.value;
  const fields = searchRef.value.fields && searchRef.value.fields();
  displayList.value = fields.slice(columnsPerRow.value);
  searchRef.value.display(advanceShow.value, displayList.value);
  searchWarp.value.calculateScrollHeight()
};

// 计算每行能容纳的列数
const filterFn = (columnsRow) => {
  const fields = searchRef.value.fields && searchRef.value.fields();
  filterShow.value = fields && fields.length > columnsRow;
};

// 初始化和监听窗口变化
const updateCurrentSpan = () => {
  const width = window.innerWidth;
  const span = getSpanByBreakpoint(width);
  columnsPerRow.value = Math.floor(24 / span);
  filterFn(columnsPerRow.value);
};

watch(
  () => columnsPerRow.value,
  (val) => {
    nextTick(async () => {
      if (val && !advanceShow.value) {
        const fields = searchRef.value.fields && searchRef.value.fields();
        fields.map(item=>{
          searchRef.value.display(fields.slice(0, val).includes(item), item);
        })
      }
    });
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  updateCurrentSpan();
  window.addEventListener("resize", debounce(updateCurrentSpan, 300));
});

onUnmounted(() => {
  window.removeEventListener("resize", updateCurrentSpan);
});
</script>

<style lang="scss" scoped></style>
